package com.mycjj.android.activity;

import java.util.Calendar;
import java.util.Map;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mycjj.android.R;
import com.mycjj.android.adapter.ProviceCityAreaAdapter;
import com.mycjj.android.bean.TreeElement;
import com.mycjj.android.db.CityAreaTable;
import com.mycjj.android.util.Utils;
import com.mycjj.android.widget.wheel.OnWheelScrollListener;
import com.mycjj.android.widget.wheel.WheelView;

public class Register2Activity extends BaseActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register2);
		mActManager.pushActivity(REGISTER_KEY, this);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		initHeader();
		init();
		initWheel();
		initWheel1();
	}

	private ImageView mHeaderLeftImageview;
	private Button mHeaderRightButton;
	private TextView mHeaderTitleTextView;
	private EditText mEt_username, mEt_tel, mEt_car_num, mEt_car_frame_num, mEt_car_engine_num;
	private TextView mTv_city, mTv_car, mTv_car_buy_time, mTv_car_check_end_time;
	private Button mBtn_man, mBtn_woman;
	private Button mBtn_submit;
	private int sex = 1;
	private View mLl_area;
	private View mLl_plate_area;
	private TextView tv_plate_area;

	private void initHeader() {
		mHeaderLeftImageview = (ImageView) findViewById(R.id.header_left_button);
		mHeaderLeftImageview.setImageResource(R.drawable.back);
		mHeaderRightButton = (Button) findViewById(R.id.header_right_button);
		mHeaderRightButton.setVisibility(View.GONE);
		mHeaderTitleTextView = (TextView) findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("注册");
		mHeaderLeftImageview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mActManager.popActivity(REGISTER_KEY, Register2Activity.this);
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			mActManager.popActivity(REGISTER_KEY, Register2Activity.this);
		}
		return super.onKeyDown(keyCode, event);
	}

	private void init() {
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		Intent intent = getIntent();
		String tel = "";
		if (intent != null) {
			tel = intent.getStringExtra("tel");
		}
		mEt_username = (EditText) findViewById(R.id.et_username);
		mEt_tel = (EditText) findViewById(R.id.et_tel);
		if(TextUtils.isEmpty(tel)){
			mEt_tel.setEnabled(true);
		}else{
			mEt_tel.setEnabled(false);
		}
		mEt_tel.setText(tel);
		
		mEt_car_num = (EditText) findViewById(R.id.et_car_num);
		mEt_car_frame_num = (EditText) findViewById(R.id.et_car_frame_num);
		mEt_car_engine_num = (EditText) findViewById(R.id.et_car_engine_num);
		mLl_area = findViewById(R.id.ll_area);
		
		mTv_city = (TextView) findViewById(R.id.tv_city);
		mTv_city.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mLl_plate_area.getVisibility() == View.VISIBLE) {
					mLl_plate_area.setVisibility(View.GONE);
				}
				hideSoftInput();
				if (mLl_area.getVisibility() == View.VISIBLE) {
					mLl_area.setVisibility(View.GONE);
				} else {
					mLl_area.setVisibility(View.VISIBLE);
				}

			}
		});
		mLl_plate_area = findViewById(R.id.ll_plate_area);
		tv_plate_area = (TextView) findViewById(R.id.tv_plate_area);
		tv_plate_area.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mLl_area.getVisibility() == View.VISIBLE) {
					mLl_area.setVisibility(View.GONE);
				}
				hideSoftInput();
				if (mLl_plate_area.getVisibility() == View.VISIBLE) {
					mLl_plate_area.setVisibility(View.GONE);
				} else {
					mLl_plate_area.setVisibility(View.VISIBLE);
				}

			}
		});
		
		
		
		mTv_car = (TextView) findViewById(R.id.tv_car);
		mTv_car.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Register2Activity.this, BrandActivity.class);
				startActivity(intent);
				// getSelectCarModle();
			}
		});
		mTv_car_buy_time = (TextView) findViewById(R.id.tv_car_buy_time);
		mTv_car_check_end_time = (TextView) findViewById(R.id.tv_car_check_end_time);
		mTv_car_buy_time.setText(mYear + "-" + Utils.pad(mMonth + 1) + "-" + Utils.pad(mDay));
		mTv_car_check_end_time.setText(mYear + "-" + Utils.pad(mMonth + 1) + "-" + Utils.pad(mDay));
		mTv_car_buy_time.setOnClickListener(showDateChooseListener);
		mTv_car_check_end_time.setOnClickListener(showDateChooseListener);

		mBtn_man = (Button) findViewById(R.id.btn_sex_man);
		mBtn_woman = (Button) findViewById(R.id.btn_sex_woman);
		mBtn_man.setOnClickListener(sexChangeListener);
		mBtn_woman.setOnClickListener(sexChangeListener);
		mBtn_submit = (Button) findViewById(R.id.btn_submit);
		mBtn_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				submit();
			}
		});
	}
	
	private void hideSoftInput(){
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEt_username.getWindowToken(), 0); 
		imm.hideSoftInputFromWindow(mEt_car_num.getWindowToken(), 0); 
		imm.hideSoftInputFromWindow(mEt_car_frame_num.getWindowToken(), 0); 
		imm.hideSoftInputFromWindow(mEt_car_engine_num.getWindowToken(), 0);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			if (mLl_area.getVisibility() == View.VISIBLE) {
				mLl_area.setVisibility(View.GONE);
			}

			if (mLl_plate_area.getVisibility() == View.VISIBLE) {
				mLl_plate_area.setVisibility(View.GONE);
			}
		}
		return super.onTouchEvent(event);
	}

	private Map<String, Integer> provinceMap;
	private Map<String, Integer> cityMap;
	private Map<String, Integer> areaMap;

	private String[] provinceArray;
	private String[] cityArray;
	private String[] areaArray;

	private WheelView provinceWheelView;
	private WheelView cityWheelView;
	private WheelView areaWheelView;

	private ProviceCityAreaAdapter provinceAdapter;
	private ProviceCityAreaAdapter cityAdapter;
	private ProviceCityAreaAdapter areaAdapter;
	private int areaId;
	private int cityId;
	private int provinceId;

	private void initWheel() {
		Button btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLl_area.setVisibility(View.GONE);
			}
		});

		Button btn_sure = (Button) findViewById(R.id.btn_sure);
		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				StringBuilder sb = new StringBuilder();
				sb.append(provinceArray[provinceWheelView.getCurrentItem()]);
				sb.append(cityArray[cityWheelView.getCurrentItem()]);
				sb.append(areaArray[areaWheelView.getCurrentItem()]);
				mTv_city.setText(sb.toString());
				areaId = areaMap.get(areaArray[areaWheelView.getCurrentItem()]);
				cityId = cityMap.get(cityArray[cityWheelView.getCurrentItem()]);
				provinceId = provinceMap.get(provinceArray[provinceWheelView.getCurrentItem()]);
				Log.d("mark", "areaId:" + areaId + ";cityId:" + cityId + ";provinceId:" + provinceId);
				mLl_area.setVisibility(View.GONE);
			}
		});
		provinceWheelView = (WheelView) findViewById(R.id.provice);
		cityWheelView = (WheelView) findViewById(R.id.city);
		areaWheelView = (WheelView) findViewById(R.id.area);

		// 初始化省滚轮列表选择器
		initProviceMap();
		provinceAdapter = new ProviceCityAreaAdapter(this, provinceArray, 0);
		provinceWheelView.setViewAdapter(provinceAdapter);
		provinceWheelView.setCurrentItem(0);
		provinceWheelView.addScrollingListener(privinceScrollListener);

		// 初始化城市滚轮列表选择器
		String provinceName = provinceArray[0];
		int cityId = provinceMap.get(provinceName);
		initCityMap(cityId);

		cityAdapter = new ProviceCityAreaAdapter(this, cityArray, 0);
		cityWheelView.setViewAdapter(cityAdapter);
		cityWheelView.setCurrentItem(0);
		cityWheelView.addScrollingListener(cityScrollListener);

		// 初始化地区滚轮列表选择器
		String cityName = cityArray[0];
		int areaId = cityMap.get(cityName);

		initAreaMap(areaId);
		areaAdapter = new ProviceCityAreaAdapter(this, areaArray, 0);
		areaWheelView.setViewAdapter(areaAdapter);
		areaWheelView.setCurrentItem(0);
	}

	OnWheelScrollListener privinceScrollListener = new OnWheelScrollListener() {

		@Override
		public void onScrollingStarted(WheelView wheel) {
		}

		@Override
		public void onScrollingFinished(WheelView wheel) {
			int currentItem = wheel.getCurrentItem();
			String provinceName = provinceArray[currentItem];
			int provinceId = provinceMap.get(provinceName);
			initCityMap(provinceId);
			cityAdapter = new ProviceCityAreaAdapter(Register2Activity.this, cityArray, 0);
			cityWheelView.setViewAdapter(cityAdapter);
			cityWheelView.setCurrentItem(0);

			String cityName = cityArray[0];
			int cityId = cityMap.get(cityName);
			initAreaMap(cityId);
			areaAdapter = new ProviceCityAreaAdapter(Register2Activity.this, areaArray, 0);
			areaWheelView.setViewAdapter(areaAdapter);
			areaWheelView.setCurrentItem(0);
		}
	};

	OnWheelScrollListener cityScrollListener = new OnWheelScrollListener() {

		@Override
		public void onScrollingStarted(WheelView wheel) {
		}

		@Override
		public void onScrollingFinished(WheelView wheel) {
			int areaId = cityMap.get(cityArray[wheel.getCurrentItem()]);
			initAreaMap(areaId);
			areaAdapter = new ProviceCityAreaAdapter(Register2Activity.this, areaArray, 0);
			areaWheelView.setViewAdapter(areaAdapter);
			areaWheelView.setCurrentItem(0);
		}
	};

	public void initProviceMap() {
		provinceMap = CityAreaTable.getProvince();
		provinceArray = provinceMap.keySet().toArray(new String[provinceMap.size()]);
	}

	public void initCityMap(int proId) {
		cityMap = CityAreaTable.getCity(proId);
		cityArray = cityMap.keySet().toArray(new String[cityMap.size()]);
	}

	public void initAreaMap(int cityId) {
		areaMap = CityAreaTable.getArea(cityId);
		areaArray = areaMap.keySet().toArray(new String[areaMap.size()]);
	}

	

	private int currentClickId;
	static final int DATE_DIALOG_ID = 1;
	static final int DATE_DIALOG1_ID = DATE_DIALOG_ID + 1;
	private int mYear;
	private int mMonth;
	private int mDay;
	private OnClickListener showDateChooseListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			currentClickId = v.getId();
			switch (v.getId()) {
			case R.id.tv_car_buy_time:
				showDialog(DATE_DIALOG_ID);
				break;
			case R.id.tv_car_check_end_time:
				showDialog(DATE_DIALOG1_ID);
				break;
			}

		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID: {
			DatePickerDialog picker = new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
			picker.setTitle("请选择购车时间");
			return picker;
		}

		case DATE_DIALOG1_ID: {
			DatePickerDialog picker = new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
			picker.setTitle("请选择年检到期时间");
			return picker;
		}

		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;

			String time = year + "-" + Utils.pad(monthOfYear + 1) + "-" + Utils.pad(dayOfMonth);
			Log.e("mark", "time:" + time);
			switch (currentClickId) {
			case R.id.tv_car_buy_time:
				mTv_car_buy_time.setText(time);
				break;
			case R.id.tv_car_check_end_time:
				mTv_car_check_end_time.setText(time);
				break;
			}
		}
	};

	private OnClickListener sexChangeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			v.setBackgroundResource(R.drawable.iv_sex_sel);
			switch (v.getId()) {
			case R.id.btn_sex_man:
				sex = 1;
				mBtn_woman.setBackgroundResource(R.drawable.iv_sex_unsel);
				break;
			case R.id.btn_sex_woman:
				sex = 2;
				mBtn_man.setBackgroundResource(R.drawable.iv_sex_unsel);
				break;
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		TreeElement element = dataManager.getElement();
		if (element != null) {
			mTv_car.setText(element.getTitle());
		}
	}

	private void submit() {
		String username = mEt_username.getText().toString().trim();
		if (TextUtils.isEmpty(username)) {
			Toast.makeText(this, "用户名不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}

		String tel = mEt_tel.getText().toString().trim();
		if (TextUtils.isEmpty(tel)) {
			Toast.makeText(this, "手机号不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}
		
		String palteArea = tv_plate_area.getText().toString().trim();
		if (TextUtils.isEmpty(palteArea) || "请选择".equals(palteArea)) {
			Toast.makeText(this, "请选择车牌地区！", Toast.LENGTH_SHORT).show();
			return;
		}
		
		String carNum = mEt_car_num.getText().toString().trim();
		if (TextUtils.isEmpty(carNum)) {
			Toast.makeText(this, "车牌不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}else if(carNum.length() > 5){
			Toast.makeText(this, "车牌号最多输入5位!", Toast.LENGTH_SHORT).show();
			return;
		}

		String carFrameNum = mEt_car_frame_num.getText().toString().trim();
		if (TextUtils.isEmpty(carFrameNum)) {
			Toast.makeText(this, "车架号不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}

		String carEngineNum = mEt_car_engine_num.getText().toString().trim();
		if (TextUtils.isEmpty(carEngineNum)) {
			Toast.makeText(this, "发动机编号不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}

		String city = mTv_city.getText().toString().trim();
		if (TextUtils.isEmpty(city) || "请选择".equals(city)) {
			Toast.makeText(this, "请选择城市", Toast.LENGTH_SHORT).show();
			return;
		}

		TreeElement element = dataManager.getElement();
		if (element == null) {
			Toast.makeText(mApp, "请选择车辆!", Toast.LENGTH_SHORT).show();
			return;
		}

		String buyCarTime = mTv_car_buy_time.getText().toString().trim();
		if (TextUtils.isEmpty(buyCarTime) || "请选择".equals(buyCarTime)) {
			Toast.makeText(this, "请选择购车时间", Toast.LENGTH_SHORT).show();
			return;
		}
		String checkEndTime = mTv_car_check_end_time.getText().toString().trim();
		if (TextUtils.isEmpty(checkEndTime) || "请选择".equals(checkEndTime)) {
			Toast.makeText(this, "请选择到期时间", Toast.LENGTH_SHORT).show();
			return;
		}

		Intent intent = new Intent(this, BindStoreActivity.class);
		intent.putExtra("type_action", 0);
		Bundle bundle = new Bundle();
		bundle.putString("username", username);
		bundle.putString("tel", tel);
		bundle.putString("carNum", carNum);
		bundle.putString("carFrameNum", carFrameNum);
		bundle.putString("carEngineNum", carEngineNum);
		bundle.putInt("areaId", areaId);
		bundle.putInt("cityId", cityId);
		bundle.putInt("provinceId", provinceId);
		bundle.putString("buyCarTime", buyCarTime);
		bundle.putString("checkEndTime", checkEndTime);
		bundle.putInt("sex", sex);
		String brandName = element.getTitle();
		String brandId1 = element.getBrandId();
		String brandId2 = element.getBrandId1();
		String brandId3 = element.getBrandId2();
		String brandId4 = element.getBrandId3();
		Log.e("mark", "register2 获得的品牌参数 brandName:"+brandName+";brandId1:"+brandId1+";brandId2:"+brandId2+";brandId3:"+brandId3+";brandId4:"+brandId4);
		bundle.putString("brand1_id", brandId1);
		bundle.putString("brand2_id", brandId2);
		bundle.putString("brand3_id", brandId3);
		bundle.putString("brand4_id", brandId4);
		bundle.putString("plate_area", palteArea);
		bundle.putString("city_code_id", String.valueOf(cityId1));
		intent.putExtras(bundle);
		startActivity(intent);
	}

	private Map<String, Integer> provinceMap1;
	private Map<String, Integer> cityMap1;

	private String[] provinceArray1;
	private String[] cityArray1;
	private String[] areaArray1;

	private WheelView provinceWheelView1;
	private WheelView cityWheelView1;
	private WheelView areaWheelView1;

	private ProviceCityAreaAdapter provinceAdapter1;
	private ProviceCityAreaAdapter cityAdapter1;
	private ProviceCityAreaAdapter areaAdapter1;
	private String areaId1;
	private int cityId1;
	private String provinceId1;

	private void initWheel1() {
		
		Button btn_cancel1 = (Button) findViewById(R.id.btn_cancel1);
		btn_cancel1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLl_plate_area.setVisibility(View.GONE);
			}
		});

		Button btn_sure1 = (Button) findViewById(R.id.btn_sure1);
		btn_sure1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				StringBuilder sb = new StringBuilder();
				sb.append(provinceArray1[provinceWheelView1.getCurrentItem()]);
				sb.append(areaArray1[areaWheelView1.getCurrentItem()]);
				Log.e("mark", "tv_plate_area:"+sb.toString());
				tv_plate_area.setText(sb.toString().trim());
				areaId1 = areaArray1[areaWheelView1.getCurrentItem()];
				cityId1 = cityMap1.get(cityArray1[cityWheelView1.getCurrentItem()]);
				provinceId1 = provinceArray1[provinceWheelView1.getCurrentItem()];
				Log.d("mark", "areaId1:" + areaId1 + ";cityId1："+cityId1+";provinceId1:" + provinceId1);
				mLl_plate_area.setVisibility(View.GONE);
			}
		});

		provinceWheelView1 = (WheelView) findViewById(R.id.provice_1);
		cityWheelView1 = (WheelView) findViewById(R.id.city_1);
		areaWheelView1 = (WheelView) findViewById(R.id.area_1);

		// 初始化省滚轮列表选择器
		initProviceMap1();
		provinceAdapter1 = new ProviceCityAreaAdapter(this, provinceArray1, 0);
		provinceWheelView1.setViewAdapter(provinceAdapter1);
		provinceWheelView1.setCurrentItem(0);
		provinceWheelView1.addScrollingListener(privinceScrollListener1);

		// 初始化城市滚轮列表选择器
		String provinceName = provinceArray1[0];
		int cityId = provinceMap1.get(provinceName);
		initCityMap1(provinceName);

		cityAdapter1 = new ProviceCityAreaAdapter(this, cityArray1, 0);
		cityWheelView1.setViewAdapter(cityAdapter1);
		cityWheelView1.setCurrentItem(0);
		cityWheelView1.addScrollingListener(cityScrollListener1);

		// 初始化地区滚轮列表选择器
		String cityName = cityArray1[0];
		int areaId = cityMap1.get(cityName);

		initAreaMap1(areaId);
		areaAdapter1 = new ProviceCityAreaAdapter(this, areaArray1, 0);
		areaWheelView1.setViewAdapter(areaAdapter1);
		areaWheelView1.setCurrentItem(0);
	}

	OnWheelScrollListener privinceScrollListener1 = new OnWheelScrollListener() {

		@Override
		public void onScrollingStarted(WheelView wheel) {
		}

		@Override
		public void onScrollingFinished(WheelView wheel) {
			int currentItem = wheel.getCurrentItem();
			String provinceName = provinceArray1[currentItem];
			initCityMap1(provinceName);
			cityAdapter1 = new ProviceCityAreaAdapter(Register2Activity.this, cityArray1, 0);
			cityWheelView1.setViewAdapter(cityAdapter1);
			cityWheelView1.setCurrentItem(0);

			String cityName = cityArray1[0];
			int cityId = cityMap1.get(cityName);
			initAreaMap1(cityId);
			areaAdapter1 = new ProviceCityAreaAdapter(Register2Activity.this, areaArray1, 0);
			areaWheelView1.setViewAdapter(areaAdapter1);
			areaWheelView1.setCurrentItem(0);
		}
	};

	OnWheelScrollListener cityScrollListener1 = new OnWheelScrollListener() {

		@Override
		public void onScrollingStarted(WheelView wheel) {
		}

		@Override
		public void onScrollingFinished(WheelView wheel) {
			int areaId = cityMap1.get(cityArray1[wheel.getCurrentItem()]);
			initAreaMap1(areaId);
			areaAdapter1 = new ProviceCityAreaAdapter(Register2Activity.this, areaArray1, 0);
			areaWheelView1.setViewAdapter(areaAdapter1);
			areaWheelView1.setCurrentItem(0);
		}
	};

	public void initProviceMap1() {
		provinceMap1 = CityAreaTable.getPlatProvince();
		provinceArray1 = provinceMap1.keySet().toArray(new String[provinceMap1.size()]);
	}

	public void initCityMap1(String attr) {
		cityMap1 = CityAreaTable.getPlateCity(attr);
		cityArray1 = cityMap1.keySet().toArray(new String[cityMap1.size()]);
	}

	public void initAreaMap1(int cityId) {
//		areaArray1 = areaMap1.keySet().toArray(new String[areaMap.size()]);
		areaArray1 = getResources().getStringArray(R.array.string_array);
	}
}
